<template>
  <div class="team-members">
    <!-- 头部信息 -->
    <div class="header-section">
      <div class="team-info">
        <el-button type="text" @click="goBack" class="back-btn">
          <el-icon><ArrowLeft /></el-icon>
          返回团队列表
        </el-button>
        <h2 class="team-title">{{ teamInfo.name }} - 团队成员</h2>
        <p class="team-desc">{{ teamInfo.description }}</p>
      </div>
      <div class="action-buttons">
        <el-button type="primary" @click="handleAddMember">
          <el-icon><Plus /></el-icon>
          添加成员
        </el-button>
        <el-button type="success" @click="handleBatchInvite">
          <el-icon><Message /></el-icon>
          批量邀请测评
        </el-button>
        <el-button type="info" @click="handleExportMembers">
          <el-icon><Download /></el-icon>
          导出成员
        </el-button>
      </div>
    </div>

    <!-- 统计卡片 -->
    <div class="stats-cards">
      <div class="stat-card">
        <div class="stat-icon primary">
          <el-icon><User /></el-icon>
        </div>
        <div class="stat-content">
          <h3>{{ memberStats.total }}</h3>
          <p>总成员数</p>
        </div>
      </div>
      <div class="stat-card">
        <div class="stat-icon success">
          <el-icon><CircleCheck /></el-icon>
        </div>
        <div class="stat-content">
          <h3>{{ memberStats.completed }}</h3>
          <p>已完成测评</p>
        </div>
      </div>
      <div class="stat-card">
        <div class="stat-icon warning">
          <el-icon><Clock /></el-icon>
        </div>
        <div class="stat-content">
          <h3>{{ memberStats.pending }}</h3>
          <p>待测评</p>
        </div>
      </div>
      <div class="stat-card">
        <div class="stat-icon info">
          <el-icon><Promotion /></el-icon>
        </div>
        <div class="stat-content">
          <h3>{{ memberStats.completionRate }}%</h3>
          <p>完成率</p>
        </div>
      </div>
    </div>

    <!-- 搜索和筛选 -->
    <div class="filter-section">
      <el-form :model="filterForm" inline>
        <el-form-item label="姓名搜索">
          <el-input
            v-model="filterForm.keyword"
            placeholder="输入姓名或工号搜索"
            @input="handleSearch"
            clearable
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="部门">
          <el-select v-model="filterForm.department" placeholder="选择部门" clearable @change="handleFilter">
            <el-option label="全部部门" value="" />
            <el-option label="技术部" value="技术部" />
            <el-option label="产品部" value="产品部" />
            <el-option label="运营部" value="运营部" />
            <el-option label="市场部" value="市场部" />
          </el-select>
        </el-form-item>
        <el-form-item label="职位">
          <el-select v-model="filterForm.position" placeholder="选择职位" clearable @change="handleFilter">
            <el-option label="全部职位" value="" />
            <el-option label="前端工程师" value="前端工程师" />
            <el-option label="后端工程师" value="后端工程师" />
            <el-option label="产品经理" value="产品经理" />
            <el-option label="UI设计师" value="UI设计师" />
            <el-option label="测试工程师" value="测试工程师" />
          </el-select>
        </el-form-item>
        <el-form-item label="测评状态">
          <el-select v-model="filterForm.status" placeholder="测评状态" clearable @change="handleFilter">
            <el-option label="全部状态" value="" />
            <el-option label="已完成" value="completed" />
            <el-option label="进行中" value="in-progress" />
            <el-option label="未开始" value="not-started" />
          </el-select>
        </el-form-item>
      </el-form>
    </div>

    <!-- 成员列表 -->
    <div class="members-table">
      <el-table :data="filteredMembers" v-loading="loading" style="width: 100%">
        <el-table-column type="selection" width="55" />
        <el-table-column label="员工信息" width="250">
          <template #default="scope">
            <div class="member-info">
              <el-avatar :size="40" :src="scope.row.avatar">
                {{ scope.row.name.charAt(0) }}
              </el-avatar>
              <div class="member-details">
                <div class="member-name">{{ scope.row.name }}</div>
                <div class="member-id">工号: {{ scope.row.employeeId }}</div>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="department" label="部门" width="120" />
        <el-table-column prop="position" label="职位" width="150" />
        <el-table-column prop="email" label="邮箱" width="200" />
        <el-table-column prop="phone" label="手机号" width="130" />
        <el-table-column label="测评状态" width="120">
          <template #default="scope">
            <el-tag
              :type="getStatusTagType(scope.row.assessmentStatus)"
              effect="light"
            >
              {{ getStatusText(scope.row.assessmentStatus) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="joinTime" label="加入时间" width="180" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button 
              type="primary" 
              size="small" 
              @click="handleInviteAssessment(scope.row)"
              :disabled="scope.row.assessmentStatus === 'completed'"
            >
              邀请测评
            </el-button>
            <el-button type="danger" size="small" @click="handleRemoveMember(scope.row)">
              移除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 添加成员对话框 -->
    <el-dialog v-model="addMemberDialogVisible" title="添加团队成员" width="600px">
      <div class="add-member-tabs">
        <el-tabs v-model="addMemberActiveTab">
          <el-tab-pane label="选择现有员工" name="existing">
            <div class="employee-search">
              <el-input
                v-model="employeeSearchKeyword"
                placeholder="搜索员工姓名或工号"
                @input="searchEmployees"
                clearable
              >
                <template #prefix>
                  <el-icon><Search /></el-icon>
                </template>
              </el-input>
            </div>
            <div class="employee-list">
              <el-table
                :data="availableEmployees"
                @selection-change="handleEmployeeSelectionChange"
                max-height="400"
              >
                <el-table-column type="selection" width="55" />
                <el-table-column label="员工信息" width="200">
                  <template #default="scope">
                    <div class="member-info">
                      <el-avatar :size="32" :src="scope.row.avatar">
                        {{ scope.row.name.charAt(0) }}
                      </el-avatar>
                      <div class="member-details">
                        <div class="member-name">{{ scope.row.name }}</div>
                        <div class="member-id">{{ scope.row.employeeId }}</div>
                      </div>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column prop="department" label="部门" />
                <el-table-column prop="position" label="职位" />
              </el-table>
            </div>
          </el-tab-pane>
          <el-tab-pane label="邀请外部人员" name="external">
            <el-form :model="externalMemberForm" :rules="externalMemberRules" ref="externalMemberFormRef" label-width="80px">
              <el-form-item label="姓名" prop="name">
                <el-input v-model="externalMemberForm.name" placeholder="请输入姓名" />
              </el-form-item>
              <el-form-item label="邮箱" prop="email">
                <el-input v-model="externalMemberForm.email" placeholder="请输入邮箱地址" />
              </el-form-item>
              <el-form-item label="手机号" prop="phone">
                <el-input v-model="externalMemberForm.phone" placeholder="请输入手机号" />
              </el-form-item>
              <el-form-item label="职位" prop="position">
                <el-input v-model="externalMemberForm.position" placeholder="请输入职位" />
              </el-form-item>
              <el-form-item label="备注">
                <el-input
                  v-model="externalMemberForm.remark"
                  type="textarea"
                  rows="3"
                  placeholder="请输入备注信息（可选）"
                />
              </el-form-item>
            </el-form>
          </el-tab-pane>
        </el-tabs>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addMemberDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleConfirmAddMember">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  ArrowLeft, Plus, Message, Download, User, CircleCheck, Clock, 
  Promotion, Search
} from '@element-plus/icons-vue'

const router = useRouter()
const route = useRoute()

// 响应式数据
const loading = ref(false)
const addMemberDialogVisible = ref(false)
const addMemberActiveTab = ref('existing')
const employeeSearchKeyword = ref('')
const externalMemberFormRef = ref()
const selectedEmployees = ref([])

// 团队信息
const teamInfo = reactive({
  id: 1,
  name: '产品研发团队',
  description: '负责核心产品的研发与技术创新，包含前端、后端、UI/UX等多个角色'
})

// 筛选表单
const filterForm = reactive({
  keyword: '',
  department: '',
  position: '',
  status: ''
})

// 外部成员表单
const externalMemberForm = reactive({
  name: '',
  email: '',
  phone: '',
  position: '',
  remark: ''
})

// 外部成员表单验证规则
const externalMemberRules = {
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  position: [
    { required: true, message: '请输入职位', trigger: 'blur' }
  ]
}

// 分页数据
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 团队成员数据
const members = ref([
  {
    id: 1,
    name: '张三',
    employeeId: 'EMP001',
    department: '技术部',
    position: '前端工程师',
    email: 'zhangsan@company.com',
    phone: '13812345678',
    avatar: '',
    assessmentStatus: 'completed',
    joinTime: '2024-08-01 09:00:00'
  },
  {
    id: 2,
    name: '李四',
    employeeId: 'EMP002',
    department: '技术部',
    position: '后端工程师',
    email: 'lisi@company.com',
    phone: '13887654321',
    avatar: '',
    assessmentStatus: 'in-progress',
    joinTime: '2024-08-02 10:30:00'
  },
  {
    id: 3,
    name: '王五',
    employeeId: 'EMP003',
    department: '产品部',
    position: '产品经理',
    email: 'wangwu@company.com',
    phone: '13898765432',
    avatar: '',
    assessmentStatus: 'not-started',
    joinTime: '2024-08-03 14:15:00'
  },
  {
    id: 4,
    name: '赵六',
    employeeId: 'EMP004',
    department: '技术部',
    position: 'UI设计师',
    email: 'zhaoliu@company.com',
    phone: '13765432109',
    avatar: '',
    assessmentStatus: 'completed',
    joinTime: '2024-08-04 11:20:00'
  },
  {
    id: 5,
    name: '钱七',
    employeeId: 'EMP005',
    department: '技术部',
    position: '测试工程师',
    email: 'qianqi@company.com',
    phone: '13654321098',
    avatar: '',
    assessmentStatus: 'not-started',
    joinTime: '2024-08-05 16:45:00'
  }
])

// 可选择的员工列表
const availableEmployees = ref([
  {
    id: 101,
    name: '孙八',
    employeeId: 'EMP101',
    department: '市场部',
    position: '市场专员',
    avatar: ''
  },
  {
    id: 102,
    name: '周九',
    employeeId: 'EMP102',
    department: '运营部',
    position: '运营经理',
    avatar: ''
  },
  {
    id: 103,
    name: '吴十',
    employeeId: 'EMP103',
    department: '技术部',
    position: '架构师',
    avatar: ''
  }
])

// 计算属性
const memberStats = computed(() => {
  const total = members.value.length
  const completed = members.value.filter(m => m.assessmentStatus === 'completed').length
  const pending = members.value.filter(m => m.assessmentStatus !== 'completed').length
  const completionRate = total > 0 ? Math.round((completed / total) * 100) : 0
  
  return { total, completed, pending, completionRate }
})

const filteredMembers = computed(() => {
  let result = members.value

  // 关键词搜索
  if (filterForm.keyword) {
    result = result.filter(member => 
      member.name.includes(filterForm.keyword) || 
      member.employeeId.includes(filterForm.keyword)
    )
  }

  // 部门筛选
  if (filterForm.department) {
    result = result.filter(member => member.department === filterForm.department)
  }

  // 职位筛选
  if (filterForm.position) {
    result = result.filter(member => member.position === filterForm.position)
  }

  // 状态筛选
  if (filterForm.status) {
    result = result.filter(member => member.assessmentStatus === filterForm.status)
  }

  pagination.total = result.length
  return result
})

// 方法
const goBack = () => {
  router.push('/dashboard/assessment/team')
}

const getStatusTagType = (status) => {
  const statusMap = {
    'completed': 'success',
    'in-progress': 'warning',
    'not-started': 'info'
  }
  return statusMap[status] || 'info'
}

const getStatusText = (status) => {
  const statusMap = {
    'completed': '已完成',
    'in-progress': '进行中',
    'not-started': '未开始'
  }
  return statusMap[status] || '未知'
}

const handleSearch = () => {
  // 搜索逻辑已在计算属性中处理
}

const handleFilter = () => {
  // 筛选逻辑已在计算属性中处理
}

const handleAddMember = () => {
  addMemberDialogVisible.value = true
  addMemberActiveTab.value = 'existing'
}

const handleBatchInvite = () => {
  const pendingMembers = members.value.filter(m => m.assessmentStatus !== 'completed')
  if (pendingMembers.length === 0) {
    ElMessage.warning('所有成员都已完成测评')
    return
  }
  
  ElMessageBox.confirm(
    `确定要向 ${pendingMembers.length} 位未完成测评的成员发送邀请吗？`,
    '批量邀请测评',
    {
      confirmButtonText: '确定发送',
      cancelButtonText: '取消',
      type: 'info'
    }
  ).then(() => {
    ElMessage.success(`已向 ${pendingMembers.length} 位成员发送测评邀请`)
  }).catch(() => {
    // 用户取消
  })
}

const handleExportMembers = () => {
  ElMessage.success('团队成员信息导出成功')
}

const handleInviteAssessment = (member) => {
  if (member.assessmentStatus === 'completed') {
    ElMessage.warning('该成员已完成测评')
    return
  }
  
  ElMessageBox.confirm(
    `确定要向 ${member.name} 发送测评邀请吗？`,
    '邀请测评',
    {
      confirmButtonText: '确定发送',
      cancelButtonText: '取消',
      type: 'info'
    }
  ).then(() => {
    // 模拟发送邀请
    if (member.assessmentStatus === 'not-started') {
      member.assessmentStatus = 'in-progress'
    }
    ElMessage.success(`已向 ${member.name} 发送测评邀请`)
  }).catch(() => {
    // 用户取消
  })
}

const handleRemoveMember = (member) => {
  ElMessageBox.confirm(
    `确定要将 ${member.name} 从团队中移除吗？`,
    '移除成员',
    {
      confirmButtonText: '确定移除',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    const index = members.value.findIndex(m => m.id === member.id)
    if (index > -1) {
      members.value.splice(index, 1)
      ElMessage.success(`${member.name} 已从团队中移除`)
    }
  }).catch(() => {
    // 用户取消
  })
}

const searchEmployees = () => {
  // 这里可以添加搜索员工的逻辑
  console.log('搜索员工:', employeeSearchKeyword.value)
}

const handleEmployeeSelectionChange = (selection) => {
  selectedEmployees.value = selection
}

const handleConfirmAddMember = async () => {
  if (addMemberActiveTab.value === 'existing') {
    if (selectedEmployees.value.length === 0) {
      ElMessage.warning('请选择要添加的员工')
      return
    }
    
    // 添加选中的员工
    selectedEmployees.value.forEach(employee => {
      const newMember = {
        id: Date.now() + Math.random(),
        name: employee.name,
        employeeId: employee.employeeId,
        department: employee.department,
        position: employee.position,
        email: `${employee.employeeId.toLowerCase()}@company.com`,
        phone: '138' + Math.random().toString().slice(2, 10),
        avatar: employee.avatar,
        assessmentStatus: 'not-started',
        joinTime: new Date().toLocaleString('zh-CN')
      }
      members.value.push(newMember)
    })
    
    ElMessage.success(`成功添加 ${selectedEmployees.value.length} 位成员`)
    addMemberDialogVisible.value = false
    selectedEmployees.value = []
    
  } else if (addMemberActiveTab.value === 'external') {
    try {
      await externalMemberFormRef.value.validate()
      
      // 添加外部成员
      const newMember = {
        id: Date.now(),
        name: externalMemberForm.name,
        employeeId: 'EXT' + Date.now().toString().slice(-6),
        department: '外部',
        position: externalMemberForm.position,
        email: externalMemberForm.email,
        phone: externalMemberForm.phone,
        avatar: '',
        assessmentStatus: 'not-started',
        joinTime: new Date().toLocaleString('zh-CN')
      }
      
      members.value.push(newMember)
      ElMessage.success(`成功添加外部成员 ${externalMemberForm.name}`)
      
      // 重置表单
      Object.keys(externalMemberForm).forEach(key => {
        externalMemberForm[key] = ''
      })
      
      addMemberDialogVisible.value = false
      
    } catch (error) {
      console.error('表单验证失败:', error)
    }
  }
}

const handleSizeChange = (val) => {
  pagination.pageSize = val
}

const handleCurrentChange = (val) => {
  pagination.currentPage = val
}

onMounted(() => {
  // 初始化数据
  pagination.total = members.value.length
})
</script>

<style scoped>
.team-members {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.header-section {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  padding: 24px;
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
}

.back-btn {
  color: white !important;
  padding: 8px 0;
  margin-bottom: 12px;
  font-size: 14px;
}

.back-btn:hover {
  background: rgba(255, 255, 255, 0.1) !important;
}

.team-title {
  margin: 0 0 8px 0;
  font-size: 24px;
  font-weight: 600;
}

.team-desc {
  margin: 0;
  opacity: 0.9;
  font-size: 14px;
  line-height: 1.5;
}

.action-buttons {
  display: flex;
  gap: 12px;
}

.action-buttons .el-button {
  background: rgba(255, 255, 255, 0.2);
  border: 1px solid rgba(255, 255, 255, 0.3);
  color: white;
}

.action-buttons .el-button:hover {
  background: rgba(255, 255, 255, 0.3);
}

.stats-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 20px;
  padding: 24px;
  background: #f8fafc;
}

.stat-card {
  background: white;
  border-radius: 8px;
  padding: 20px;
  display: flex;
  align-items: center;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
  transition: transform 0.2s;
}

.stat-card:hover {
  transform: translateY(-2px);
}

.stat-icon {
  width: 48px;
  height: 48px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 16px;
  font-size: 20px;
}

.stat-icon.primary {
  background: #e3f2fd;
  color: #1976d2;
}

.stat-icon.success {
  background: #e8f5e8;
  color: #388e3c;
}

.stat-icon.warning {
  background: #fff3e0;
  color: #f57c00;
}

.stat-icon.info {
  background: #f3e5f5;
  color: #7b1fa2;
}

.stat-content h3 {
  margin: 0 0 4px 0;
  font-size: 24px;
  font-weight: 600;
  color: #1a202c;
}

.stat-content p {
  margin: 0;
  font-size: 14px;
  color: #718096;
}

.filter-section {
  padding: 20px 24px;
  background: white;
  border-bottom: 1px solid #e5e7eb;
}

.members-table {
  padding: 24px;
}

.member-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.member-details {
  flex: 1;
}

.member-name {
  font-weight: 500;
  color: #1a202c;
  margin-bottom: 2px;
}

.member-id {
  font-size: 12px;
  color: #718096;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 24px;
  padding-top: 24px;
  border-top: 1px solid #e5e7eb;
}

.add-member-tabs {
  margin-top: 16px;
}

.employee-search {
  margin-bottom: 16px;
}

.employee-list {
  max-height: 400px;
  overflow-y: auto;
}

:deep(.el-table th) {
  background: #f8fafc !important;
  color: #374151;
  font-weight: 600;
}

:deep(.el-table td) {
  padding: 16px 0;
}

:deep(.el-button + .el-button) {
  margin-left: 8px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}
</style>
